﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Runtime;

namespace Client
{
    class ListProcesses
    {
        #region -  VARIABLES  -
        public static bool isRepeat = false;        
        public static List<string> listProcesses = null;
        private static StringBuilder sb = null;
        #endregion

        #region -  THREAD  -
        private static Thread repeatGetListProcesses = null;
        #endregion

        #region -  EVENT  -
        public static event GetListProcessesEventHandler OnGetListProcesses = null;
        #endregion

        #region -  INITIALIZE  -
        public static void Initialize()
        { 
            listProcesses = new List<string>();
            
        }
        #endregion 

        #region -  START GET LIST PROCESSES  -
        public static void StartGetListProcesses()
        {
            repeatGetListProcesses = new Thread(new ThreadStart(GetListProcesses));
            repeatGetListProcesses.Start();
        }
        #endregion

        #region -  STOP GET LIST PROCESSES  -
        public static void StopGetListProcesses()
        {
            if (repeatGetListProcesses != null)
            {
                repeatGetListProcesses.Abort();
            }
        }
        #endregion

        #region -  GET LIST PROCESSES  -
        public static void GetListProcesses()
        {
            while (true)
            {
                Thread.Sleep(1500);
                sb = new StringBuilder();
                int mem = 0;
                foreach (Process p in Process.GetProcesses())
                {
                    mem = (int)(p.WorkingSet64 / 1024);
                    sb.Append(p.Id.ToString() + "|" + p.ProcessName + "|" + mem.ToString() + "|");
                }
                if (OnGetListProcesses != null)
                {
                    OnGetListProcesses(null, new GetListProcessesEventArgs(sb.ToString()));
                }
            }
        }
        #endregion

        #region -  KILL PROCESS  -
        public static void KillPrcess(string name)
        {
            try
            {
                foreach (Process p in Process.GetProcesses())
                {
                    if (p.ProcessName.Equals(name))
                    {
                        p.Kill();
                    }
                }
            }
            catch 
            {}
        }
        #endregion        

        #region -  STOP THREAD  -
        public static void StopDenyProcess()
        {
            try
            {
                if (repeatGetListProcesses != null)
                {
                    repeatGetListProcesses.Abort();
                }
            }
            catch
            {}
        }
        #endregion
    }
}
